<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               v-model:search="search"
               v-model:page="page"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template #menu-left>
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.tasktemplate_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-button type="primary"
                   size="small"
                   icon="el-icon-position"
                   plain
                   v-if="permission.tasktemplate_edit"
                   @click="handleCopyTask">批量复制
        </el-button>
      </template>
      <template #menu="{row}">
        <el-button text
                   size="small"
                   type="primary"
                   icon="el-icon-position"
                   v-if="permission.tasktemplate_edit"
                   @click="rowCopyTask(row)">复 制
        </el-button>
      </template>
      <template #status="{row}">
        <el-switch v-model="row.status" :active-value="1" :inactive-value="0" disabled></el-switch>
      </template>
      <template #areaId="{row}">
        <el-tag >{{row.$areaId}}</el-tag>
      </template>
      <template #userId="{row}">
        <el-tag >{{row.$userId}}</el-tag>
      </template>

      <template #timeRule="{row}">
        <el-tag v-if="row.cycle === 2">{{ getWeek(row.timeValue) + ' ' + row.timeRule }}</el-tag>
        <el-tag v-else-if="row.cycle === 3">{{ '每月' + row.timeValue + '日 ' + row.timeRule }}</el-tag>
        <el-tag v-else>{{ row.timeRule }}</el-tag>
      </template>

      <template #timeRule-form>
        <el-input v-model="form.timeRule" placeholder="请输入时间（格式：HH:mm）">
          <template #prepend v-if="form.cycle === 2 || form.cycle === 3">
            <el-select v-model="form.timeValue" placeholder="选择 星期" style="width: 115px" v-if="form.cycle === 2">
              <el-option :label="item.label" :value="item.value" v-for="item in weekData" />
            </el-select>
            <el-select v-model="form.timeValue" placeholder="选择 月" style="width: 115px" v-if="form.cycle === 3">
              <el-option :label="i" :value="i" v-for="i in 31" />
            </el-select>
          </template>
        </el-input>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove, copyTask } from '@/api/restaurant/tasktemplate';
import { mapGetters } from 'vuex';
import { baseUrl } from '@/config/env';
import func from '@/utils/func';
import { getAreaTree } from '@/api/restaurant/area';
import { getUserAttendance } from '@/api/restaurant/common';
import { getWeek } from '@/utils/util';

export default {
  data() {
    return {
      form: {},
      query: {},
      search: {},
      loading: true,
      weekData: [
        {
          label: '星期一',
          value: 2
        },
        {
          label: '星期二',
          value: 3
        },
        {
          label: '星期三',
          value: 4
        },
        {
          label: '星期四',
          value: 5
        },
        {
          label: '星期五',
          value: 6
        },
        {
          label: '星期六',
          value: 7
        },
        {
          label: '星期日',
          value: 1
        }
      ],
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 210,
        labelWidth: 150,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        column: [
          {
            label: '任务名',
            prop: 'taskName',
            rules: [{
              required: true,
              message: '请输入任务名',
              trigger: 'blur'
            }]
          },
          {
            label: '任务类型',
            prop: 'timeType',
            type: 'select',
            search: true,
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: baseUrl + '/blade-system/dict/dictionary?code=task_time_type',
            rules: [{
              required: true,
              message: '请输入任务类型',
              trigger: 'blur'
            }]
          },

          {
            label: '分配区域',
            prop: 'areaId',
            multiple: false,
            filterable: true,
            type: 'tree',
            dicData: [],
            props: {
              label: 'title'
            },
            slot: true,
            checkStrictly: true,
            rules: [{
              required: false,
              message: '请分配区域',
              trigger: 'click'
            }]
          },
          {
            label: '下发人',
            prop: 'userId',
            multiple: false,
            filterable: true,
            type: 'tree',
            dicUrl: baseUrl + '/restaurant/common/userAttendance',
            dicData: [],
            slot: true,
            checkStrictly: true,
            rules: [{
              required: true,
              message: '请输入下发人',
              trigger: 'click'
            }]
          },
          {
            label: '任务周期',
            type: 'select',
            dicUrl: baseUrl + '/blade-system/dict/dictionary?code=task_cycle',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            slot: true,
            prop: 'cycle',
            search: true,
            rules: [{
              required: true,
              message: '请输入任务周期',
              trigger: 'blur'
            }]
          },
          {
            label: '时间规则',
            prop: 'timeRule',
            type: 'time',
            rules: [{
              required: true,
              message: '请输入时间规则',
              trigger: 'blur'
            }]
          },
          {
            label: '执行截止时间',
            prop: 'deadline',
            type: 'time',
            format: 'HH:mm',
            valueFormat: 'HH:mm',
            rules: [{
              required: true,
              message: '请输入执行截止时间',
              trigger: 'blur'
            }]
          },
          {
            label: '检查截止时间',
            prop: 'inspectDeadline',
            type: 'time',
            format: 'HH:mm',
            valueFormat: 'HH:mm',
            rules: [{
              required: true,
              message: '请输入检查截止时间',
              trigger: 'blur'
            }]
          },
          {
            label: '状态',
            prop: 'status',
            type: 'switch',
            search: true,
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=task_status',
            rules: [{
              required: true,
              message: '请输入状态',
              trigger: 'blur'
            }]
          },
          {
            label: '注意事项',
            prop: 'announcements',
            overHidden: true,
            component: 'avue-ueditor',
            span: 24,
            minRows: 4,
            type: 'textarea',
            rules: [{
              required: true,
              message: '请输入注意事项',
              trigger: 'blur'
            }]
          },
          {
            label: '示例图',
            prop: 'sampleGraph',
            type: 'upload',
            overHidden: true,
            listType: 'picture-card',
            action: '/api/blade-resource/oss/endpoint/put-file',
            propsHttp: {
              res: 'data',
              url: 'link'
            },
            span: 24,
            rules: [{
              required: false,
              message: '请输入示例图',
              trigger: 'blur'
            }]
          },
          {
            label: '最近下发',
            prop: 'lastTime',
            editDisplay: false,
            addDisplay: false,
            rules: [{
              required: false,
              message: '请输入最近下发',
              trigger: 'blur'
            }]
          },
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.tasktemplate_add, false),
        viewBtn: this.validData(this.permission.tasktemplate_view, false),
        delBtn: this.validData(this.permission.tasktemplate_delete, false),
        editBtn: this.validData(this.permission.tasktemplate_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    getWeek,

    rowSave(row, done, loading) {
      if (Array.isArray(row.sampleGraph)) {
        row.sampleGraph = func.join(row.sampleGraph);
      }

      add(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      if (Array.isArray(row.sampleGraph)) {
        row.sampleGraph = func.join(row.sampleGraph);
      }
      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },

    rowCopyTask(row) {
      this.$confirm('确定将选择数据进行复制?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return copyTask(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },

    handleCopyTask() {

      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }

      this.$confirm('确定将选择数据进行复制?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return copyTask(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;

        getAreaTree().then(res => {
          const column = this.findObject(this.option.column, 'areaId');
          column.dicData = res.data.data;
        });
        getUserAttendance().then(res => {
          const column = this.findObject(this.option.column, 'userId');
          column.dicData = res.data.data;
        });
        this.selectionClear();
      });
    }
  }
};
</script>

<style>
</style>
